
<!DOCTYPE html>
<html lang="UTF-8" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="">
  <meta name="author" content="">

  <link rel="stylesheet" th:href="@{/bootstrap/css/bootstrap.min.css}">
  <link rel="stylesheet" th:href="@{/css/font-awesome.min.css}">
  <link rel="stylesheet" th:href="@{/css/login.css}">
  <link rel="stylesheet" th:href="@{/css/main.css}">
  <link rel="stylesheet" type="text/css" th:href="@{/css/pagination.css}">
  <script src="/layer/layer.js" th:src="@{/text/javascript}"></script>
  <style>
    .tree li {
      list-style-type: none;
      cursor:pointer;
    }
    .tree-closed {
      height : 40px;
    }
    .tree-expanded {
      height : auto;
    }
  </style>
</head>

<body>


<div th:replace="~{include-nav :: nav}"></div>

<div class="container-fluid">
  <div class="row">
    <div th:replace="~{include-modal-role-confirm :: roleconfirm}"></div>
    <div th:replace="~{include-nav :: sidebar}"></div>
    <div th:replace="~{include-modal-role-add :: roleadd}"></div>
    <div th:replace="~{include-modal-role-edit :: roleedit}"></div>

    <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
      <div class="panel panel-default">
        <div class="panel-heading">
          <h3 class="panel-title"><i class="glyphicon glyphicon-th"></i> 数据列表</h3>
        </div>
        <div class="panel-body">
          <form th:action="@{/admin/query/for/search}" method="post" class="form-inline" role="form" style="float:left;">
            <div class="form-group has-feedback">
              <div class="input-group">
                <div class="input-group-addon">查询条件</div>
                <input id="keywordInput" class="form-control has-success" type="text" placeholder="请输入查询条件">
              </div>
            </div>
            <button id="searchBtn" type="button" class="btn btn-warning"><i class="glyphicon glyphicon-search"></i> 查询</button>
          </form>

          <button id="batchRemoveBtn" type="button" class="btn btn-danger" style="float:right;margin-left:10px;">
            <i class=" glyphicon glyphicon-remove"></i> 删除
          </button>

          <button id="addBtn" type="button" class="btn btn-primary" style="float:right;">
            <i class="glyphicon glyphicon-plus"></i> 新增
          </button>



          <br>
          <hr style="clear:both;">
          <div class="table-responsive">
            <table class="table  table-bordered">

              <thead>
              <tr >
                <th width="30">#</th>
                <th width="30"><input id="summaryBox" type="checkbox"></th>
                <th>名称</th>
                <th width="100">操作</th>
              </tr>
              </thead>






              <tbody id="roleTableBody">
              <!--ajax加载数据-->
              </tbody>

              <tfoot>
              <tr >
                <td colspan="4" align="center">
                  <div id="Pagination" class="pagination">
                    <!-- 这里显示分页 -->
                  </div>
                </td>
              </tr>
              </tfoot>

            </table>
          </div>
        </div>
      </div>
    </div>


  </div>

</div>

<script th:src="@{/jquery/jquery-2.1.1.min.js}"></script>
<script th:src="@{/bootstrap/js/bootstrap.min.js}"></script>
<script th:src="@{/script/docs.min.js}"></script>
<script type="text/javascript" th:src="@{/script/jquery.pagination.js}"></script>
<link rel="stylesheet" type="text/css" href="/css/pagination.css"/>
<script type="text/javascript" src="/script/my-role.js"></script>
<script src="/layer/layer.js" th:src="@{/text/javascript}"></script>

<script type="text/javascript">
  $(function () {
    //定义全局变量
    window.pageSize = 2;
    window.pageNum = 1;
    window.keyword = "";
    //显示数据
    showPage();
  });



  function showPage() {
    $.ajax({
      url:"/role/search/by/keyword",
      type:"post",
      data:{
        "pageNum":window.pageNum,
        "pageSize":window.pageSize,
        "keyword":window.keyword
      },
      dataType:"json",
      success:function (result) {
        if(result.result=="SUCCESS"){
          //解析数据
          $("#roleTableBody").empty();
          // 获取数据集合
          var list = result.data.list;
          // 判断list是否有效
          if(list == null || list.length == 0) {
            $("#roleTableBody")
                    .append("<tr><td colspan='4' style='text-align:center;'>没有查询到数据！</td></tr>");

            return ;
          }
          for(var i = 0; i < list.length; i++) {
            var role = list[i];

            //数据
            var numberTd = "<td>"+(i+1)+"</td>";
            var checkBoxTd = "<td><input class='itemBox' roleid='"+role.id+"' type='checkbox'></td>";
            var roleNameTd = "<td>"+role.name+"</td>";

            //按钮
            var checkBtn = "<button type='button' class='btn btn-success btn-xs'><i class=' glyphicon glyphicon-check'></i></button>";
            var pencilBtn = "<button roleId='"+role.id+"' type='button' class='btn btn-primary btn-xs editBtn'><i class=' glyphicon glyphicon-pencil'></i></button>";
            var removeBtn = "<button roleId='"+role.id+"' type='button' class='btn btn-danger btn-xs removeBtn'><i class=' glyphicon glyphicon-remove'></i></button>";

            var btnTd = "<td>"+checkBtn+" "+pencilBtn+" "+removeBtn+"</td>";

            var tr = "<tr>"+numberTd+checkBoxTd+roleNameTd+btnTd+"</tr>";

            // 将前面拼好的HTML代码追加到#roleTableBody中
            $("#roleTableBody").append(tr);
          }

          //显示分页导航
          initPagination(result.data);
        }else{
          layer.msg(result.message);
        }
      }
    });
  }

  //声明函数封装导航条初始化操作
  function initPagination(pageInfo) {

    // 声明变量存储分页导航条显示时的属性设置
    var paginationProperties = {
      num_edge_entries : 3,        //边缘页数
      num_display_entries : 5,      //主体页数
      callback : pageselectCallback, //回调函数
      items_per_page : window.pageSize,  //每页显示数据数量，就是pageSize
      current_page : (window.pageNum - 1),//当前页页码
      prev_text : "上一页",       //上一页文本
      next_text : "下一页"        //下一页文本
    };

    // 显示分页导航条
    $("#Pagination").pagination(pageInfo.total, paginationProperties);
  }


  // 在每一次点击“上一页”、“下一页”、“页码”时执行这个函数跳转页面
  function pageselectCallback(pageIndex,jq) {
    // 将全局变量中的pageNum修改为最新值
    // pageIndex从0开始，pageNum从1开始
    window.pageNum = pageIndex + 1;
    // 调用分页函数重新执行分页
    showPage();
    return false;
  }

  //关键字查询
  $("#searchBtn").click(function(){
    // 在单击响应函数中获取文本框中输入的数据
    var keyword = $.trim($("#keywordInput").val());

    // 验证输入数据是否有效
    if(keyword == null || keyword == "") {
      // 如果无效，提示，停止函数执行
      layer.msg("请输入关键词！");
      return ;
    }

    // 如果有效，赋值给window.keyword
    window.keyword = keyword;

    // 调用showPage()重新分页
    showPage();
  });
  // 全选/全不选功能
  $("#summaryBox").click(function(){
    // 1.获取当前checkbox的选中状态
    var currentStatus = this.checked;
    // 2.设置itemBox的选中状态
    $(".itemBox").prop("checked",currentStatus);

  });
  $("#batchRemoveBtn").click(function () {
    // 获取被选中的itemBox数组长度
    var length = $(".itemBox:checked").length;

    // 如果长度为0，说明没有选择itemBox
    if(length == 0) {
      layer.msg("请至少选择一条！");
      return ;
    }
  });
  $("#batchRemoveBtn").click(function () {
    // 获取被选中的itemBox数组长度
    var length = $(".itemBox:checked").length;

    // 如果长度为0，说明没有选择itemBox
    if(length == 0) {
      layer.msg("请至少选择一条！");
      return ;
    }

    // 在全局作用域内创建roleIdArray
    window.roleIdArray = new Array();

    // 遍历$(".itemBox:checked")
    $(".itemBox:checked").each(function(){

      // 通过checkbox的roleid属性获取roleId值
      var roleId = $(this).attr("roleid");

      // 存入数组
      window.roleIdArray.push(roleId);

    });
    //alert(window.roleIdArray);

    // 调用函数打开模态框
    showRemoveConfirmModal();
  });
  function showRemoveConfirmModal() {
    // 1.将模态框显示出来
    $("#confirmModal").modal("show");

    //显示要删除的数据
    var requestBody = JSON.stringify(window.roleIdArray);
    // 2.发送Ajax请求
    var ajaxResult = $.ajax({
      url:"/role/get/list/by/id/list",
      type:"post",
      data:requestBody,
      contentType:"application/json;charset=UTF-8",
      dataType:"json",
      success:function (ajaxResult) {
        if(ajaxResult.result == "SUCCESS") {
          // 5.如果成功，显示数据
          // 3.清空#confirmModalTableBody
          $("#confirmModalTableBody").empty();
          // 4.填充#confirmModalTableBody
          var roleList =ajaxResult.data;
          for(var i = 0; i < roleList.length; i++) {

            // 5.获取角色相关数据
            var role = roleList[i];

            var id = role.id;

            var name = role.name;

            var trHTML = "<tr><td>"+id+"</td><td>"+name+"</td></tr>";

            // 6.执行填充
            $("#confirmModalTableBody").append(trHTML);
          }
        } else{
          layer.msg(ajaxResult.message);
          return null;
        }
      }
    });
  }
  //确认删除
  $("#confirmModalBtn").click(function () {
    var requestBody = JSON.stringify(window.roleIdArray);
    $.ajax({
      url:"/role/batch/remove",
      type:"post",
      data:requestBody,
      contentType:"application/json;charset=UTF-8",
      dataType:"json",
      success:function(response){
        var result = response.result;
        if(result == "SUCCESS") {
          layer.msg("操作成功！");
          // 如果删除成功，则重新调用分页方法
          showPage();
        }
        if(result == "FAILED") {
          layer.msg(response.message);
        }
        // 不管成功还是失败，都需要关掉模态框
        $("#confirmModal").modal("hide");

      },
      "error":function(response){
        layer.msg(response.message);
      }
    });
  })
  //单条删除
  $('#roleTableBody').on("click",".removeBtn",function () {
    // 获取当前记录的roleId
    var roleId = $(this).attr("roleId");
    // 存入全局变量数组
    window.roleIdArray = new Array();
    window.roleIdArray.push(roleId);
    // 打开模态框（后续所有操作都和批量删除一样）
    showRemoveConfirmModal();
  });


  //添加
  //增加
  $("#addBtn").click(function(){
    $("#addModal").modal("show");
  });



  //确认添加
  $("#addModalBtn").click(function () {
    // 1.收集文本框内容
    var roleName = $.trim($("#roleNameInput").val());
    if(roleName == null || roleName == "") {
      layer.msg("请输入有效角色名称！");
      return ;
    }
    $.ajax({
      url:"/role/save/role",
      type:"post",
      data:{
        "roleName":roleName
      },
      dataType:"json",
      success:function (response) {
        var result = response.result;
        if(result == "SUCCESS") {
          layer.msg("操作成功！");
          // 前往最后一页
          window.pageNum = 999999;
          showPage();
          // 不管成功还是失败，关闭模态框
          $("#addModal").modal("hide");

          // 清理本次在文本框填写的数据
          $("#roleNameInput").val("");
        }else {
          layer.msg(response.message);
        }
      }
    });
  });
  //修改
  $("#roleTableBody").on("click",".editBtn",function(){

    // 1.获取当前按钮的roleId
    window.roleId = $(this).attr("roleId");

    // 2.获取当前按钮所在行的roleName
    var roleName = $(this).parents("tr").children("td:eq(2)").text();

    // 3.修改模态框中文本框的value值，目的是在显示roleName
    $("#roleNameInputEdit").val(roleName);

    // 4.打开模态框
    $("#editModal").modal("show");
  });

  //确认修改
  $("#editModalBtn").click(function () {
    // 1.获取文本框值
    var roleName = $.trim($("#roleNameInputEdit").val());

    if(roleName == null || roleName == "") {
      layer.msg("请输入有效角色名称！");

      return ;
    }
    $.ajax({
      url:"/role/update/role",
      type:"post",
      data:{
        "id":window.roleId,
        "name":roleName
      },
      dataType:"json",
      success:function (response) {
        var result = response.result;
        if(result == "SUCCESS") {
          layer.msg("操作成功！");
          // 3.操作成功重新分页
          showPage();
        }
        if(result == "FAILED") {
          layer.msg(response.message);
        }

        // 4.不管成功还是失败，关闭模态框
        $("#editModal").modal("hide");
      }
    });
  });

</script>
</body>
</html>